import re

# ====================== 统计函数定义 ======================
def count_chars(content):
    """统计所有字符（包括空格、换行、标点）"""
    return len(content)

def count_words(content):
    """统计英文单词（连续字母序列，忽略数字和符号）"""
    words = re.findall(r'[a-zA-Z]+', content)
    return len(words)

def count_sentences(content):
    """统计句子（以.?!结尾的视为句子）"""
    sentences = [s.strip() for s in re.split(r'[.!?]', content) if s.strip()]
    return len(sentences)

def count_lines(content):
    """统计总行数"""
    return len(content.split('\n'))

def count_blank_lines(content):
    """统计空行（全为空白字符或空）"""
    lines = content.split('\n')
    return sum(1 for line in lines if not line.strip())

def count_comment_lines(lines):
    """统计注释行（以//开头的行）"""
    return sum(1 for line in lines if line.strip().startswith('//'))

def count_code_lines(lines):
    """统计代码行（非空且非注释行）"""
    return sum(1 for line in lines if line.strip() and not line.strip().startswith('//'))

# ====================== 主程序执行 ======================
if __name__ == "__main__":
    # 定义要统计的文件名（可根据需要修改）
    filename = "example.txt"
    
    try:
        # 读取文件内容
        with open(filename, 'r', encoding='utf-8') as f:
            content = f.read()
        lines = content.split('\n')  # 预处理行数据
        
        # 计算所有统计指标
        chars = count_chars(content)
        words = count_words(content)
        sentences = count_sentences(content)
        total_lines = count_lines(content)
        blank_lines = count_blank_lines(content)
        comment_lines = count_comment_lines(lines)
        code_lines = count_code_lines(lines)
        
        # 格式化输出结果
        print(f"===== {filename} 统计结果 =====")
        print(f"字符数：{chars}")
        print(f"单词数：{words}")
        print(f"句子数：{sentences}")
        print(f"总行数：{total_lines}")
        print(f"空行数：{blank_lines}")
        print(f"注释行数：{comment_lines}")
        print(f"代码行数：{code_lines}")
        print("==========================")
        
    except FileNotFoundError:
        print(f"错误：未找到文件 '{filename}'，请确保该文件与wc.py在同一文件夹")
    except UnicodeDecodeError:
        print(f"错误：文件 '{filename}' 编码错误，请保存为UTF-8格式")
    except Exception as e:
        print(f"运行出错：{str(e)}")